﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using CxExtension;
namespace FSM
{
	public class StateNode:Condition
	{
		private ListNode enter;
		private HashSet<Condition> logic_orignal = new HashSet<Condition>();
		private HashSet<Condition> logic_rutime = new HashSet<Condition>();
		private HashSet<Condition> logic_remove = new HashSet<Condition>();
		private HashSet<Condition> logic_addill = new HashSet<Condition>();
		private ListNode leave;
		private bool runtime = false;
		private bool isAddill = false;
		private bool isRemoved = false;
		protected override void OnEnter()
		{
			base.OnEnter();
			logic_rutime.Clear();
			logic_remove.Clear();
			foreach(var item in logic_orignal)
			{
				item.Enter();
				logic_rutime.Add(item);
			}
			if(enter)
			{
				enter.Enter();
			}
		}
		public void AddLogic(Condition cod)
		{
			logic_orignal.Add(cod);
		}
		public void AddLogicRuntime(Condition cod)
		{
			if(runtime)
			{
				isAddill = true;
				logic_addill.Add(cod);
			}
			else
			{
				logic_rutime.Add(cod);
			}
		}
		protected override bool OnUpdate()
		{
			runtime = true;
			isRemoved = false;
			foreach(var it in logic_rutime)
			{
				if(it.Update())
				{
					isRemoved = true;
					logic_remove.Add(it);
				}
			}
			runtime = false;
			logic_rutime.Add(logic_addill,ref isAddill);
			logic_rutime.Remove(logic_remove,ref isRemoved);
			/* if(isAddill)
			 {
				 foreach(var item in logic_addill)
				 {
					 logic_rutime.Add(item);
				 }
				 logic_addill.Clear();
			 }
			 if(isRemoved)
			 {
				 foreach(var item in logic_remove)
				 {
					 logic_rutime.Remove(item);
				 }
				 logic_remove.Clear();
				 isRemoved = false;
			 }*/
			return false;
		}
		protected override void OnLeave()
		{
			base.OnLeave();
			if(enter)
			{
				enter.Leave();
			}
			foreach(var it in logic_orignal)
			{
				it.Leave();
			}
			// if(update)
			{
				//update.Leave();
			}
			if(leave)
			{
				leave.Update();
				leave.Leave();
			}
		}
	}
}